require 'digest/sha1'

class User < ActiveRecord::Base
  validates_length_of :username, :within => 3..40
  validates_length_of :clearpassword, :within => 5..40
  validates_presence_of :username, :email, :clearpassword, :clearpassword_confirmation, :firstname, :lastname, :address, :city, :postalcode, :county
  validates_uniqueness_of :username, :email
  validates_confirmation_of :clearpassword
  validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :message => "Invalid email"
  
  attr_protected :id
  attr_accessor :clearpassword, :clearpassword_confirmation

  has_many :ads
  has_many :active_ads, :class_name => "Ad", :finder_sql => 'SELECT ads.* FROM ads WHERE ads.user_id=#{id} AND ads.enddate > "#{Time.now.to_formatted_s(:db)}"'
  has_many :inactive_ads, :class_name => "Ad", :finder_sql => 'SELECT ads.* FROM ads WHERE ads.user_id=#{id} AND ads.enddate < "#{Time.now.to_formatted_s(:db)}"'
  has_many :picture_owners
  has_many :pictures, :through => :picture_owners
  has_many :ad_subscriptions
  has_many :category_subscriptions
  has_many :bids
  has_many :judgements, :class_name => "Judgement", :finder_sql => 'SELECT judgements.* FROM judgements WHERE seller_id = #{id} OR buyer_id = #{id}'
  #maximum bid per auction insted of all bids per auction
  has_many :maxbids, :class_name => "Bid", :finder_sql => 'SELECT bids.*, MAX(bids.max) as max FROM bids WHERE bids.user_id = #{id} GROUP BY bids.auction_id, bids.user_id'
  belongs_to :county
  has_one :admin_user
  
  def self.authenticate(email, pass)
    u=find(:first, :conditions=>["email = ?", email])
    #logger.debug "Found #{u.username} #{u.password} encpwd is #{User.encrypt(pass, email)}"
    return nil if u.nil?
    return u if User.encrypt(pass)==u.password
    nil
  end

  def clearpassword=(pass)
    @clearpassword = pass
    self.password = User.encrypt(@clearpassword)
    #logger.debug "Setting password to #{self.password} #{User.encrypt(@clearpassword, self.email)}"
  end

  def to_param
    "#{id}-" + username.downcase.gsub(/[åä]+/,'a').gsub(/[ö]+/,'o').gsub(/[^a-z0-9\s_-]+/,'').gsub(/[\s_-]+/,'-')
  end

  protected

  #email is used as salt
  def self.encrypt(pass)
    Digest::SHA1.hexdigest(pass+pass+"tradingonrails")
  end

end
